import { Form, Input, Button, Upload, message,Select,Radio  } from "antd";
import React, { Component, ReactNode } from "react";
const { Option } = Select;
import { Editor } from "react-draft-wysiwyg";
import { convertToRaw, EditorState, ContentState } from "draft-js";
import draftToHtml from "draftjs-to-html";
import htmlToDraft from "html-to-draftjs";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { UploadOutlined } from "@ant-design/icons";
import { instance } from '../../utils/request';
import { url } from "inspector";
import '../../assets/style/common.scss'
interface EditGoodFormProps {
  data: any;
  visible?: boolean;
  close?: () => void;
  closeModal: () => void; // 将closeModal方法作为props传递给子组件
}

class EditNoticeFrom extends Component<EditGoodFormProps> {
  state = {
    // 富文本存储的值
    editorText: "",
    // 编辑的父文本值
    editorState: EditorState.createEmpty(), // 初始化为一个空的编辑器状态
  };
  // 执行更新操作
  onFinish = (values: any) => {
    console.log(values);
    let params = {
      notice_name: values.notice_name,
      notice_type: values.notice_type,
      notice_status: values.notice_status,
      notice_content: this.state.editorText,
    };
    instance
      .put(`/notices/${this.props.data.notice_id}`, params)
      .then((res) => {
            message.success("修改公告成功!");
            this.props.closeModal();
      })
      .catch((error) => {
        console.log("error=", error);
      });
  };

  fromRef = React.createRef<any>();
  // 获取焦点引用
  setDomEditorRef = React.createRef<any>();

  componentDidMount(): void {
    // 重新进行渲染
    // 获取 父级组件传递过来的值
    const {
      notice_name,
      notice_type,
      notice_status,
      notice_content
    } = this.props.data;

    // 填充表单，获取数据
    this.fromRef.current.setFieldsValue({
      notice_name,
      notice_type,
      notice_status,
      notice_content
    });

    // 获取焦点解析后，重新赋值
    this.setDomEditorRef.current.focusEditor();
    this.setState({
      editorState: this.transformHtmlToDraftState(notice_content),
    });
  }
  transformHtmlToDraftState = (html = "") => {
    const blocksFromHtml = htmlToDraft(html);
    const { contentBlocks, entityMap } = blocksFromHtml;
    const contentState = ContentState.createFromBlockArray(
      contentBlocks,
      entityMap
    );
    return EditorState.createWithContent(contentState);
  };

  onFinishFailed = () => {};
  handleCustomRequest = (options:any) => {
    const { file, onError, onSuccess } = options;
    const ext = file.name.split('.')[1];
    if (!['jpg', 'jpeg', 'png'].includes(ext)) {
      message.error('请上传jpg、jpeg、png格式的图片');
      onError('File format not supported');
      return;
    }
    const formData = new FormData();
    formData.append('file', file);

    instance.post("/upload", formData)
      .then((response) => {
        onSuccess(response, file);
      })
      .catch((error) => {
        onError(error);
      });
  };

  normFile = (e: any) => {
    console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    const arr = [];
    arr.push(e.fileList[e.fileList.length - 1]);

    return e && arr;
  };


  onChangeNoticeType =()=>{};

  // 富文本编辑器的内容
  onEditorStateChange = (editorState: any) => {
    // 讲富文本编辑器内容转换为字符串
    let html = draftToHtml(convertToRaw(editorState.getCurrentContent()));
    // console.log(html);

    this.setState({
      editorText: html,
      editorState: editorState,
    });
  };

  render() {
    return (
      <div>
        <Form  ref={this.fromRef} onFinish={this.onFinish} onFinishFailed={this.onFinishFailed}>
          <Form.Item
            label="公告标题"
            name="notice_name"
            rules={[{ required: true, message: "请输入公告标题" }]}
          >
            <Input />
       </Form.Item>


{/*  单选 */}
          <Form.Item
            label="公告类型"
            name="notice_type"
            rules={[{ required: true, message: "请输入公告类型" }]}
          >
            <Radio.Group onChange={this.onChangeNoticeType} value={1}>
              <Radio value={1}>通知</Radio>
              <Radio value={2}>公告</Radio>
              <Radio value={3}>提醒</Radio>
            </Radio.Group>
          </Form.Item>

          {/*下拉 */}

          <Form.Item
            label="公告状态"
            name="notice_status"
            rules={[{ required: true, message: "请输入公告状态" }]}
          >
            <Select placeholder="请选择字典状态" style={{width:'200px'}} >
              <Option value={0}>正常</Option>
              <Option value={1}>禁用</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="公告内容"
            name="notice_content"
            rules={[
              {
                validator: (rule, value, callback) => {
                  const content = this.state.editorText
                  console.log(content,'1----')
                  if (content!=='') {
                    callback();
                  } else {
                    callback("请输入公告内容详情");
                  }
                },
              },
            ]}
          >
           <div  className="editor-container">
              <Editor
                      ref={this.setDomEditorRef}
                toolbarClassName="toolbarClassName"
                wrapperClassName="wrapperClassName"
                editorClassName="editorClassName"
                onEditorStateChange={this.onEditorStateChange}
                editorState={this.state.editorState}
              />
            </div>
          </Form.Item>

          <Form.Item style={{float:'right',marginLeft:'10px'}}>
            <Button type="primary" htmlType="submit">
              发布
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

export default EditNoticeFrom;
